package com.itheima.kafka.simple;

import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Properties;

/**
 * 消息生产者
 */
public class ProducerFastStart {

    private static final String TOPIC = "itcast-topic";

    public static void main(String[] args) {

        //添加kafka的配置信息
        Properties properties = new Properties();
        //配置broker信息
        properties.put("bootstrap.servers","192.168.200.129:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        // 重试次数 默认0， kafka 冪等性操作
        properties.put(ProducerConfig.RETRIES_CONFIG,10);
//        properties.put(ProducerConfig.ACKS_CONFIG, "all");

        //生产者对象
        KafkaProducer<String,String> producer = new KafkaProducer<String, String>(properties);

        //封装消息
        ProducerRecord<String,String> record = new ProducerRecord<String, String>(TOPIC,"00001","hello kafka !");
        //发送消息
//        try {
//            producer.send(record);
//        }catch (Exception e){
//            e.printStackTrace();
//        }

        //同步发送消息：等到ACK回复 结果要成功
//        try {
//            // 消息元数据 recordMetadata
//            RecordMetadata recordMetadata = producer.send(record).get();
//            System.out.println(recordMetadata.offset());//获取偏移量  记录在 kafka的 默认的 topic中__consumer_offsets
//        }catch (Exception e){
//            e.printStackTrace();
//        }

        //发送消息
        try {
            producer.send(record, new Callback() {
                @Override
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    if(e!=null){  // 成功发送 异常则为 null,  失败则异常就不为 null
                        e.printStackTrace();
                    }
                    System.out.println(recordMetadata.offset());
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

        //关系消息通道
        producer.close();
    }
}
